from datetime import datetime, timedelta
from typing import Optional
from jose import jwt, JWTError
from fastapi import HTTPException, status, Depends
from fastapi.security import HTTPBearer
from app.core.config import settings
from passlib.context import CryptContext

# 密码加密上下文
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

security = HTTPBearer(auto_error=False)  # 设置auto_error=False，允许不带token访问

def verify_password(plain_password: str, hashed_password: str) -> bool:
    """验证密码"""
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password: str) -> str:
    """获取密码哈希值"""
    return pwd_context.hash(password)

def create_token(user_id: int, is_superuser: bool = False, expires_delta: Optional[timedelta] = None) -> str:
    to_encode = {
        "sub": str(user_id),
        "is_superuser": is_superuser
    }
    if expires_delta:
        expire = datetime.utcnow() + expires_delta
    else:
        expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)

async def verify_token(token: Optional[str] = None) -> int:
    """
    验证token,如果没有token则返回超级用户ID
    """
    try:
        if not token:
            return 1  # 返回超级用户ID
            
        payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        user_id = payload.get("sub")
        if user_id is None:
            return 1  # 返回超级用户ID
        return int(user_id)
    except (JWTError, ValueError):
        return 1  # 返回超级用户ID 

async def get_current_user(auth: Optional[HTTPBearer] = Depends(security)) -> int:
    """获取当前用户ID"""
    token = auth.credentials if auth else None
    return await verify_token(token) 